package com.buba.springcloud.service.impl;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.buba.springcloud.config.Constants;
import com.buba.springcloud.config.SftpUtil;
import com.buba.springcloud.mapper.DocumentMapper;
import com.buba.springcloud.mapper.VideoMapper;
import com.buba.springcloud.pojo.Document;
import com.buba.springcloud.pojo.Video;
import com.buba.springcloud.service.IDocumentService;
import com.buba.springcloud.service.IVideoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements IVideoService {
    @Autowired
    SftpUtil sftpUtil;

    @Override
    public String upload(MultipartFile mf, Integer userId) {
        String url = "";
        try {
            String curFileName = mf.getOriginalFilename();
            String type = mf.getContentType();
            String shortName = curFileName.substring(0,curFileName.lastIndexOf("."));
//            取消名称后带时间戳
//            String newName = curFileName.substring(0,curFileName.lastIndexOf("."))+ "_"+String.valueOf(System.currentTimeMillis()) + curFileName.substring(curFileName.lastIndexOf("."));
            //判断类型
            String[] targetType = {"video/mp4","video/x-ms-wmv","video/mpeg4","video/avi","video/wma","video/quicktime","video/x-flv","video/mpg","video/x-matroska"};
            Arrays.sort(targetType);
            int j=Arrays.binarySearch(targetType,type);
            if(j<0){
                log.error("视频类型不支持");
            }

//            if (!targetType.equals(type)) {
//                log.error("文档类型不支持");
//            }

            //上传图片

            //判断图片大小
            /*long curSize = mf.getSize();
            log.info("图片大小={}",curSize);
            long targetSize = 1 *1024;
            if (curSize > targetSize){
                throw new FebsException("图片大小不能超过" + targetSize + "byte");
            }*/

            //判断长宽
//            BufferedImage image = ImageIO.read(mf.getInputStream());
//            if (image == null) {
//                throw new FebsException("图片无法识别");
//            }

//            int curWidth = image.getWidth();
//            int curHeight = image.getHeight();
//            int targetMaxWidth = 300;
//            int targetHeigth = 720;
//            if (curWidth <= targetMaxWidth || curHeight != targetHeigth) {
//                throw new FebsException("上传的文件尺寸不符合要求，必须是：宽不超过" + targetMaxWidth + "px, 高等于" + targetHeigth+ "px");
//            }

            //由于前端读取文档不方便，所不建立新文件夹
//            String dirName = DateUtil.format(new Date(), "yyyy-MM-dd");
//            String basePath = "http://127.0.0.1:8080/";
            //服务器存放路径，开头带/，表示绝对根目录开始
//            File file = FileUtil.file(FileUtil.mkdir("/media/pdf/" + dirName), shortName);


            //存放于部署机器的路径下，上线后在服务器中会有两份
            File file = FileUtil.file(FileUtil.mkdir(Constants.videoLocalPath), shortName+".mp4");
            mf.transferTo(file);
            log.info("保存成功");

//            异地保存
            //存到远程另一种方式，jcraft方案
//            FileInputStream in = new FileInputStream(file);
//            sftpUtil.upload(Constants.videoRemotePath,shortName+".mp4", in);
//            log.info("上传成功");

            /**
             * 保存记录到数据库
             */
            Video video = new Video();
//            video.setId(58);
            video.setUserId(userId);
            video.setName(shortName);
//            用户设置类型
            video.setType(6);
            video.setUrl("/guides-web-videos/"+shortName+".mp4");
            video.setCreatedTime(new Date());
            video.setMainImage("/images/%E8%A7%86%E9%A2%91%E4%B8%BB%E5%9B%BE.jpeg");
//            前端用户选择库中链接商品ids
            video.setProductIds("38");
            this.saveOrUpdate(video);
//            this.baseMapper.insert(video);
        } catch (Exception e) {
            log.error("上传失败");
            return "null";
        }
        //待返回服务器的文件地址，暂未对url处理赋值
        return url;
    }

    @Override
    public List<Video> selectList(Integer userId) {
        QueryWrapper<Video> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.orderByDesc("created_time");
        return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    public Video detailByName(String name) {
        QueryWrapper<Video>queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        Video aResult = this.baseMapper.selectOne(queryWrapper);
        aResult.setUrl(Constants.ipAddr+aResult.getUrl());
        aResult.setMainImage(Constants.ipAddr+aResult.getMainImage());
        return aResult;
    }
}
